package qj.persistence;

import java.util.Hashtable;
import java.io.*;

/**
 * Created by QuanLA
 * Date: Mar 1, 2006
 * Time: 4:06:21 PM
 */
public class ObjectPersistence {
    private static Hashtable cache = new Hashtable();
    private static String fileDir = "c:\\temp\\cache";

    /**
     * 
     * @param name
     * @param obj
     */
    public static void saveObject(String name, Object obj) {
        cache.put(name, obj);
        try {
            File file = new File(fileDir);
            if (!file.exists()) {
                file.mkdirs();
            }

            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileDir + "\\" + name + ".obj"));
            oos.writeObject(obj);
            oos.flush();
            oos.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Get the object from cache or file system.
     * @param name
     * @return null if not found the object.
     */
    public static Object loadObject(String name) {
        ObjectInputStream ois = null;
        Object o = null;

        o = cache.get(name);

        if (o==null) {
            try {
                ois = new ObjectInputStream(new FileInputStream(fileDir + "\\" + name + ".obj"));
                o = ois.readObject();
                ois.close();
                cache.put(name, o);
            } catch (IOException e) {
                return null;
            } catch (ClassNotFoundException e) {
            	throw new RuntimeException(e);
            }

            return o;
        }
        else
            return o;

    }
}
